package com.situ.mall.web.controller;

import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.user.model.vo.LoginUserVO;
import com.situ.mall.web.service.CartFeignService;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.OrderFeignService;
import com.situ.mall.web.service.AddressFeignService;
import com.mall.user.model.vo.AddressVO;
import com.xzh.mallorderspi.model.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单控制器
 */
@Slf4j
@Controller
public class OrderController {

    @Autowired
    private OrderFeignService orderFeignService;
    
    @Autowired
    private CartFeignService cartFeignService;
    
    @Autowired
    private CategoryFeignService categoryFeignService;
    
    @Autowired
    private AddressFeignService addressFeignService;

    /**
     * 结账页面
     */
    @GetMapping("/checkout")
    public String checkout(Model model, HttpServletRequest request) {
        try {
            // 检查登录状态
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/user/login";
            }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 获取购物车中选中的商品（这里简化处理，从请求参数中获取）
            String[] selectedCartIds = request.getParameterValues("cartIds");
            if (selectedCartIds != null && selectedCartIds.length > 0) {
                // TODO: 根据选中的购物车ID获取商品信息
                // 这里先模拟订单项数据
                model.addAttribute("orderItems", createMockOrderItems());
                model.addAttribute("order", createMockOrder());
            } else {
                // 如果没有选中商品，跳转回购物车
                return "redirect:/cart";
            }

            // 获取用户地址列表
            try {
                JsonResult<List<AddressVO>> addressesResult = addressFeignService.getUserAddresses();
                if (addressesResult != null && addressesResult.isSuccess() && addressesResult.getData() != null) {
                    model.addAttribute("mas", addressesResult.getData());
                    log.info("获取用户地址: {} 个", addressesResult.getData().size());
                } else {
                    model.addAttribute("mas", java.util.Collections.emptyList());
                }
            } catch (Exception e) {
                log.error("获取用户地址失败", e);
                model.addAttribute("mas", java.util.Collections.emptyList());
            }
            
            model.addAttribute("currentUser", currentUser);

        } catch (Exception e) {
            log.error("结账页面数据加载失败", e);
            return "redirect:/cart";
        }

        return "checkout";
    }

    /**
     * 创建订单
     */
    @PostMapping("/order/create")
    @ResponseBody
    public JsonResult<?> createOrder(@RequestBody OrderCreateRequest request, HttpServletRequest httpRequest) {
        try {
            LoginUserVO currentUser = getCurrentUser(httpRequest);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

                         // 构建订单项
             OrderItem orderItem = new OrderItem();
             orderItem.setUserId(currentUser.getId());
             orderItem.setGoodId(request.getGoodId());
             orderItem.setGoodName(request.getGoodName());
             orderItem.setCount(request.getCount());
             orderItem.setDealPrice(request.getDealPrice());
             orderItem.setAddressId(1L); // 临时设置固定地址ID

            // 调用订单服务创建订单
            ResponseEntity<JsonResult<?>> result = orderFeignService.createOrder(orderItem);
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("订单创建成功: userId={}", currentUser.getId());
                return JsonResult.success(result.getBody().getData());
            } else {
                return JsonResult.fail("订单创建失败");
            }

        } catch (Exception e) {
            log.error("订单创建失败", e);
            return JsonResult.fail("订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 订单支付
     */
    @PostMapping("/order/pay")
    @ResponseBody
    public JsonResult<?> payOrder(@RequestParam("orderId") Long orderId,
                                  @RequestParam("paymentMethod") String paymentMethod,
                                  HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            // 生成支付单号（这里简化处理）
            String paymentNo = "PAY" + System.currentTimeMillis();

            ResponseEntity<JsonResult<?>> result = orderFeignService.payOrder(orderId, paymentNo);
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("订单支付成功: orderId={}, paymentNo={}", orderId, paymentNo);
                return JsonResult.success("支付成功");
            } else {
                return JsonResult.fail("支付失败");
            }

        } catch (Exception e) {
            log.error("订单支付失败: orderId={}", orderId, e);
            return JsonResult.fail("支付失败: " + e.getMessage());
        }
    }

    /**
     * 我的订单页面
     */
    @GetMapping("/my-orders")
    public String myOrders(Model model, HttpServletRequest request,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          @RequestParam(value = "status", required = false) String status) {
        try {
            // 检查登录状态
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/login";
            }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 获取用户订单列表
            ResponseEntity<JsonResult<?>> ordersResult = orderFeignService.getUserOrders(
                    page, size, currentUser.getId(), status);
            
            if (ordersResult.getBody() != null && ordersResult.getBody().isSuccess()) {
                // 这里需要根据实际返回的数据结构调整
                Object data = ordersResult.getBody().getData();
                if (data != null) {
                    // 假设返回的是Page对象
                    model.addAttribute("orders", data);
                    log.info("获取用户订单列表成功: userId={}, page={}, status={}", currentUser.getId(), page, status);
                }
            } else {
                model.addAttribute("orders", java.util.Collections.emptyList());
            }

            // 分页信息
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("currentStatus", status);
            model.addAttribute("currentUser", currentUser);

        } catch (Exception e) {
            log.error("我的订单页面数据加载失败", e);
            model.addAttribute("orders", java.util.Collections.emptyList());
        }

        return "my-orders";
    }

    /**
     * 取消订单
     */
    @PostMapping("/order/cancel")
    @ResponseBody
    public JsonResult<?> cancelOrder(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            ResponseEntity<JsonResult<?>> result = orderFeignService.updateOrderStatus(orderId, "CANCELLED");
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("订单取消成功: orderId={}, userId={}", orderId, currentUser.getId());
                return JsonResult.success("订单已取消");
            } else {
                return JsonResult.fail("取消订单失败");
            }

        } catch (Exception e) {
            log.error("取消订单失败: orderId={}", orderId, e);
            return JsonResult.fail("取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 确认收货
     */
    @PostMapping("/order/confirm")
    @ResponseBody
    public JsonResult<?> confirmDelivery(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            ResponseEntity<JsonResult<?>> result = orderFeignService.updateOrderStatus(orderId, "DELIVERED");
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("确认收货成功: orderId={}, userId={}", orderId, currentUser.getId());
                return JsonResult.success("确认收货成功");
            } else {
                return JsonResult.fail("确认收货失败");
            }

        } catch (Exception e) {
            log.error("确认收货失败: orderId={}", orderId, e);
            return JsonResult.fail("确认收货失败: " + e.getMessage());
        }
    }

    /**
     * 从Session中获取当前用户
     */
    private LoginUserVO getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object userInfo = session.getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                return (LoginUserVO) userInfo;
            }
        }
        return null;
    }

    /**
     * 创建模拟订单项（临时用于页面展示）
     */
    private List<OrderItemVO> createMockOrderItems() {
        return List.of(
            new OrderItemVO("测试商品1", new BigDecimal("99.00"), 1),
            new OrderItemVO("测试商品2", new BigDecimal("199.00"), 2)
        );
    }

    /**
     * 创建模拟订单（临时用于页面展示）
     */
    private OrderVO createMockOrder() {
        OrderVO order = new OrderVO();
        order.setTotalPay(new BigDecimal("397.00"));
        return order;
    }

    /**
     * 创建模拟地址（临时用于页面展示）
     */
    private List<String> createMockAddresses() {
        return List.of(
            "北京市朝阳区建国路1号",
            "上海市浦东新区陆家嘴路2号"
        );
    }

    // 订单创建请求DTO
    public static class OrderCreateRequest {
        private Long goodId;
        private String goodName;
        private Integer count;
        private BigDecimal dealPrice;
        private String address;

        // getters and setters
        public Long getGoodId() { return goodId; }
        public void setGoodId(Long goodId) { this.goodId = goodId; }

        public String getGoodName() { return goodName; }
        public void setGoodName(String goodName) { this.goodName = goodName; }

        public Integer getCount() { return count; }
        public void setCount(Integer count) { this.count = count; }

        public BigDecimal getDealPrice() { return dealPrice; }
        public void setDealPrice(BigDecimal dealPrice) { this.dealPrice = dealPrice; }

        public String getAddress() { return address; }
        public void setAddress(String address) { this.address = address; }
    }

    // 订单项VO
    public static class OrderItemVO {
        private String goodName;
        private BigDecimal dealPrice;
        private Integer count;

        public OrderItemVO(String goodName, BigDecimal dealPrice, Integer count) {
            this.goodName = goodName;
            this.dealPrice = dealPrice;
            this.count = count;
        }

        // getters and setters
        public String getGoodName() { return goodName; }
        public void setGoodName(String goodName) { this.goodName = goodName; }

        public BigDecimal getDealPrice() { return dealPrice; }
        public void setDealPrice(BigDecimal dealPrice) { this.dealPrice = dealPrice; }

        public Integer getCount() { return count; }
        public void setCount(Integer count) { this.count = count; }
    }

    // 订单VO
    public static class OrderVO {
        private BigDecimal totalPay;

        public BigDecimal getTotalPay() { return totalPay; }
        public void setTotalPay(BigDecimal totalPay) { this.totalPay = totalPay; }
    }
} 